// ignore_for_file: public_member_api_docs

import 'package:chathouse/pages/expert/buyWallet/recharge_bank_card.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/widgets/base_appbar.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
// Import for iOS features.
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';

import '../model/web_model.dart';
import '../public/event_bus.dart';

///WeView
class BaseWebViewPage extends StatefulWidget {
  WebModel? webModel;

  BaseWebViewPage({Key? key, @required this.webModel}) : super(key: key);

  @override
  WebViewState createState() => WebViewState(webModel);
}

class WebViewState extends State<BaseWebViewPage> {
  WebModel? webModel;

  WebViewState(this.webModel);

  double currentProgress = 0;

  late final WebViewController _controller;

  @override
  void initState() {
    super.initState();

    late final PlatformWebViewControllerCreationParams params;
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      params = WebKitWebViewControllerCreationParams(
        allowsInlineMediaPlayback: true,
        mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
      );
    } else {
      params = const PlatformWebViewControllerCreationParams();
    }

    final WebViewController controller =
        WebViewController.fromPlatformCreationParams(params);
    // #enddocregion platform_features
    controller
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            debugPrint('WebView is loading (progress : $progress%)');
            setState(() {
              currentProgress = progress.toDouble() / 100;
            });
          },
          onPageStarted: (String url) {
            debugPrint('Page started loading: $url');
          },
          onPageFinished: (String url) {
            debugPrint('Page finished loading: $url');
          },
          onWebResourceError: (WebResourceError error) {
            debugPrint('''
            Page resource error:
            code: ${error.errorCode}
            description: ${error.description}
            errorType: ${error.errorType}
            isForMainFrame: ${error.isForMainFrame}
          ''');
          },
          onNavigationRequest: (NavigationRequest request) {
            if(request.url.contains("example")) {
              eventBus.fire(UpdateMemberInfo());
              Get.back();
              Get.back();
              Get.back();
              return NavigationDecision.navigate;
            }
            if (request.url.startsWith('https://www.youtube.com/')) {
              debugPrint('blocking navigation to ${request.url}');
              return NavigationDecision.prevent;
            }
            debugPrint('allowing navigation to ${request.url}');
            return NavigationDecision.navigate;
          },
        ),
      )
      // ..addJavaScriptChannel(
      //   'Toaster',
      //   onMessageReceived: (JavaScriptMessage message) {
      //     ScaffoldMessenger.of(context).showSnackBar(
      //       SnackBar(content: Text(message.message)),
      //     );
      //   },
      // )
      ..loadRequest(Uri.parse(webModel?.url ?? ""));
    // #docregion platform_features
    if (controller.platform is AndroidWebViewController) {
      AndroidWebViewController.enableDebugging(true);
      (controller.platform as AndroidWebViewController)
          .setMediaPlaybackRequiresUserGesture(false);
    }
    // #enddocregion platform_features
    _controller = controller;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: getAppBar(title: webModel?.title ?? ""),
      body: Center(
        child: Column(
          children: [
            Visibility(
              visible: currentProgress != 1,
              child: SizedBox(
                height: 2,
                child: LinearProgressIndicator(
                  valueColor: const AlwaysStoppedAnimation<Color>(
                      Color(Styles.FFFA6C17)),
                  backgroundColor: const Color(Styles.FFCCCCCC),
                  value: currentProgress,
                ),
              ),
            ),
            Expanded(
                child: WebViewWidget(
              controller: _controller,
            )),
          ],
        ),
      ),
    );
  }
}
